package com.itcast.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itcast.dao.PermissionDao;
import com.itcast.dao.RoleDao;
import com.itcast.dao.UserDao;
import com.itcast.entity.PageResult;
import com.itcast.entity.QueryPageBean;
import com.itcast.pojo.Permission;
import com.itcast.pojo.Role;
import com.itcast.pojo.User;
import com.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
  @Autowired
  private UserDao userDao;
  @Autowired
  private RoleDao roleDao;
  @Autowired
  private PermissionDao permissionDao;
    @Override
    public User findByUsername(String username) {
        //查询用户信息
        User user = userDao.findByUserName(username);
        if (user==null){
            return null;
        }
        //根据用户id查询对应角色
        Integer userId = user.getId();
        Set<Role> roleSet = roleDao.findByUserId(userId);
        if (roleSet!=null&&roleSet.size()>0){

            for (Role role : roleSet) {
                Integer roleId = role.getId();
                //根据角色id查询权限
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                role.setPermissions(permissions);//让角色关联权限
            }
            user.setRoles(roleSet);//让用户关联角色
        }
        return user;
    }


    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<User> userPage = userDao.findAll(queryString);
        Long total = userPage.getTotal();
        List<User> rows = userPage.getResult();

        return new PageResult(total, rows);
    }
}
